package com.huanke.iot.log.service;

import java.util.Date;
import java.util.List;

import com.huanke.iot.base.po.Alarms.Alarms;
import com.huanke.iot.log.dao.AlarmDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author AAJ
 * @version 1.0
 * @date 2020/11/26
 */
@Service
public class AlarmService {

  @Autowired
  private AlarmDao alarmDao;

  public List<Alarms> findAll() {
    return alarmDao.findAll();
  }

  public Alarms addOrUpdate(Alarms alarm) {
    if (alarm.getAlarmTime() == null){
      alarm.setAlarmTime(new Date());
    }
    return alarmDao.save(alarm);
  }

  public List<Alarms> findAlarmsByMethod(String method) {
    return alarmDao.findByMethod(method);
  }
  
  public List<Alarms> saveAll(List<Alarms> alarms){
    alarms.forEach(alarm->{
      addOrUpdate(alarm);
    });
    return alarms;
  }

  /**
   * 查询最近一次该设备该DI的未处理告警记录
   * @param method
   * @param diAlarm
   * @return
   */
  public Alarms findUnhandledDIAlarm(String method, String diAlarm) {
    return alarmDao.findTopByMethodAndAlarmAndHandledOrderByAlarmTimeDesc(method,diAlarm,false);
  }

  /**
   * 查询所有该设备该DI未处理告警
   * @param deviceId
   * @param diAlarm
   * @return
   */
  public List<Alarms> findUnhandledDIAlarmList(String deviceId, String diAlarm) {
    return alarmDao.findByMethodAndAlarmAndHandled(deviceId,diAlarm,false);
  }
}
